import pygame
import random
import time


class Ball(pygame.sprite.Sprite):
    ATTACK_TB = 1
    ATTACK_LR = 2
    """
    撞击小球
    """
    def __init__(self, src, radius, vx, vy, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(src)
        self.rect = self.image.get_rect()
        self.rect.x = width / 2
        self.rect.y = height - 50
        self.radius = radius
        self.velocity_x = vx
        self.velocity_y = vy
        self.last_time = 0
        self.width = width - (radius * 2)
        self.height = height - (radius * 2)
        self.last_attack_time = [0, 0]

    def update(self, times, rate=10):
        #if times > self.last_time + rate:
        self.last_time = times
        self.rect = self.rect.move(self.velocity_x, self.velocity_y)
        self.attactBorder()
            #print("move[{},{}]".format(self.velocity_x, self.velocity_y))

    def attack(self, attack, offset=[0, 0]):
        if attack == self.ATTACK_LR:
            if time.time() - 0.1 > self.last_attack_time[0]:
                self.last_attack_time[0] = time.time()
                self.velocity_x = -self.velocity_x + random.randint(offset[0], offset[1])
        else:
            if time.time() - 0.1 > self.last_attack_time[1]:
                self.last_attack_time[1] = time.time()
                self.velocity_y = -self.velocity_y + random.randint(offset[0], offset[1])
            # print("attact {}".format(attack))

    def attactBorder(self):
        if (self.rect.x <= 0 and self.velocity_x <= 0) or (self.rect.x >= self.width and self.velocity_x >= 0):
            self.attack(self.ATTACK_LR)
        if (self.rect.y <= 0 and self.velocity_y <= 0) or (self.rect.y >= self.height and self.velocity_y >= 0):
            self.attack(self.ATTACK_TB)

